<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\model\users;

use app\common\model\base\A3Mall;
use app\common\model\Calculation;
use app\common\model\system\Setting;
use app\common\traits\recordAllRun;
use think\facade\Db;

class AccountDetails extends A3Mall{
    use recordAllRun;   //使用链表查询处理

    // 获取小数位
    const SCALE = 20;

    const TYPE_LIST = [
        'ADMIN_RECHARGE'   => [1,'后台充值','+'],   // 类型、类型说明、是否限制正负值
        'ADMIN_WITHDRAWAL'  => [51,'后台提现','-'], // 提现
        'SERVICE_CHARGE'   => [76,'服务费','-'],   // 扣除服务费
        'VIP_RENEW'   => [77,'购买VIP','-'],   // 购买vip费用
    ];

    protected $name = "account_details";

    /** 获取关联所有数据的列表
     * @param array $whereTmp  条件
     * @param array $limit  查询数量
     * @param string $order 排序
     * @param array $fields 查询字段（暂缺）
     * @return array
     */
    public function recordAll($whereTmp = [],$limit = [],$orderTmp = [],$fieldsTmp= []) {

        return $this->recordAllRun([$whereTmp,$limit,$orderTmp,$fieldsTmp],[],[
        ]);
    }



    /**
     * 添加详情记录
     * @param string $type 类型，必须为 self::TYPE_LIST 的建
     * @param $userId 用户ID
     * @param $money 变动金额
     * @param array|null $extraParams 额外参数 [relation_id、explain] 【关联ID、费用说明】
     */
    static function recordAdd(string $type,int $userId,$money,array $extraParams = null) {
        $type = self::TYPE_LIST[$type];
        /********* 判断正负限制 *****************/
        if(array_key_exists(2,$type)) {
            switch ($type[2]) {
                case '+':
                    if(bccomp($money,0,self::SCALE) == -1) {
                        return false;
                    }
                    break;
                case '-':
                    if(bccomp($money,0,self::SCALE) == 1) {
                        return false;
                    }
                    break;
            }
        }
        /******* END 判断正负限制 ***************/
        $extraParams = is_array($extraParams)?$extraParams:[];
        $data = [
            'user_id'   => $userId,
            'money' => Calculation::trimZero($money),
            'type'  => $type[0],
            'relation_id'   => array_key_exists('relation_id',$extraParams)?$extraParams['relation_id']:0,
            'explain'   => array_key_exists('explain',$extraParams)?$extraParams['explain']:'',
            'create_time'   => time(),
        ];


        // 插入并获取插入的ID
        return self::insertGetId($data);
    }

}
